<template>
  <div class="coordinate-transform-demo">
    <div class="demo-container">
      <!-- 左侧：坐标转换工具 -->
      <div class="transform-panel">
        <h2>完整坐标系转换工具</h2>
        <p class="subtitle">支持 8 种常用坐标系互相转换</p>
        
        <!-- 单点转换 -->
        <div class="section">
          <h3>单点坐标转换</h3>
          <div class="input-group">
            <label>经度:</label>
            <input v-model="singlePoint.lng" type="number" step="0.000001" placeholder="输入经度" />
            <label>纬度:</label>
            <input v-model="singlePoint.lat" type="number" step="0.000001" placeholder="输入纬度" />
            <label>源坐标系:</label>
            <select v-model="singlePoint.fromType">
              <option v-for="system in supportedSystems" :key="system" :value="system">
                {{ getSystemName(system) }}
              </option>
            </select>
            <button @click="transformSinglePoint" class="transform-btn">转换</button>
          </div>
          
          <div v-if="singlePointResult" class="result">
            <h4>转换结果:</h4>
            <div class="result-grid">
              <div v-for="system in supportedSystems" :key="system" class="result-item">
                <strong>{{ getSystemName(system) }}:</strong> 
                <span v-if="system === 'epsg3857'">
                  {{ formatCoordinate(singlePointResult[system].x, singlePointResult[system].y) }}
                </span>
                <span v-else>
                  {{ formatCoordinate(singlePointResult[system].lng, singlePointResult[system].lat) }}
                </span>
                <button 
                  v-if="system !== 'epsg3857'"
                  @click="flyToCoordinate(singlePointResult[system].lng, singlePointResult[system].lat)" 
                  class="locate-btn"
                >
                  定位
                </button>
                <span v-else class="no-locate">投影坐标</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 批量转换 -->
        <div class="section">
          <h3>批量坐标转换</h3>
          <div class="input-group">
            <label>源坐标系:</label>
            <select v-model="batchTransform.fromType">
              <option v-for="system in supportedSystems" :key="system" :value="system">
                {{ getSystemName(system) }}
              </option>
            </select>
            <label>目标坐标系:</label>
            <select v-model="batchTransform.toType">
              <option v-for="system in supportedSystems" :key="system" :value="system">
                {{ getSystemName(system) }}
              </option>
            </select>
            <label>坐标列表 (每行一个坐标，格式: lng,lat):</label>
            <textarea 
              v-model="batchTransform.coordinates" 
              placeholder="116.3913, 39.9075&#10;121.4737, 31.2304&#10;113.2644, 23.1291"
              rows="4"
            ></textarea>
            <button @click="transformBatch" class="transform-btn">批量转换</button>
          </div>
          
          <div v-if="batchResult" class="result">
            <h4>批量转换结果:</h4>
            <div class="batch-result">
              <div v-for="(coord, index) in batchResult" :key="index" class="batch-item">
                <span class="coord-index">#{{ index + 1 }}</span>
                <span class="coord-value">{{ formatCoordinate(coord.lng, coord.lat) }}</span>
                <button @click="flyToCoordinate(coord.lng, coord.lat)" class="locate-btn small">定位</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 距离计算 -->
        <div class="section">
          <h3>距离计算</h3>
          <div class="input-group">
            <div class="point-input">
              <label>点1:</label>
              <input v-model="distancePoint1.lng" type="number" step="0.000001" placeholder="经度" />
              <input v-model="distancePoint1.lat" type="number" step="0.000001" placeholder="纬度" />
            </div>
            <div class="point-input">
              <label>点2:</label>
              <input v-model="distancePoint2.lng" type="number" step="0.000001" placeholder="经度" />
              <input v-model="distancePoint2.lat" type="number" step="0.000001" placeholder="纬度" />
            </div>
            <button @click="calculateDistance" class="transform-btn">计算距离</button>
          </div>
          
          <div v-if="distanceResult" class="result">
            <h4>距离结果:</h4>
            <div class="result-item">
              <strong>距离:</strong> {{ distanceResult.toFixed(2) }} 米
            </div>
          </div>
        </div>

        <!-- 预设坐标 -->
        <div class="section">
          <h3>预设坐标示例</h3>
          <div class="preset-buttons">
            <button @click="loadPreset('beijing')">北京天安门</button>
            <button @click="loadPreset('shanghai')">上海外滩</button>
            <button @click="loadPreset('guangzhou')">广州塔</button>
            <button @click="loadPreset('shenzhen')">深圳平安金融中心</button>
            <button @click="loadPreset('xian')">西安钟楼</button>
            <button @click="loadPreset('chengdu')">成都天府广场</button>
          </div>
        </div>

        <!-- 坐标系信息 -->
        <div class="section">
          <h3>坐标系说明</h3>
          <div class="system-info">
            <div v-for="system in supportedSystems" :key="system" class="system-item">
              <div class="system-header" @click="toggleSystemInfo(system)">
                <span class="system-name">{{ getSystemName(system) }}</span>
                <span class="toggle-icon">{{ expandedSystems.includes(system) ? '−' : '+' }}</span>
              </div>
              <div v-if="expandedSystems.includes(system)" class="system-details">
                <p><strong>描述:</strong> {{ getSystemInfo(system)?.description }}</p>
                <p><strong>精度:</strong> {{ getSystemInfo(system)?.accuracy }}</p>
                <p><strong>用途:</strong> {{ getSystemInfo(system)?.usage }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：地图显示 -->
      <div class="map-container">
        <div ref="mapContainer" class="cesium-map"></div>
        <div class="map-info">
          <p>地图显示：点击"定位"按钮可以飞行到对应坐标</p>
          <p>支持坐标系：</p>
          <ul>
            <li><span class="color-dot wgs84"></span> WGS84 (GPS标准)</li>
            <li><span class="color-dot gcj02"></span> GCJ02 (中国地图)</li>
            <li><span class="color-dot bd09"></span> BD09 (百度地图)</li>
            <li><span class="color-dot cgcs2000"></span> CGCS2000 (中国官方)</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import CesiumMap from '../utils/CesiumMap';
import CoordinateTransform from '../utils/CoordinateTransform';
import * as Cesium from 'cesium';

// 地图容器引用
const mapContainer = ref(null);
let cesiumMap = null;

// 支持的坐标系列表
const supportedSystems = CoordinateTransform.getSupportedSystems();

// 展开的坐标系信息
const expandedSystems = ref(['wgs84', 'gcj02', 'bd09']);

// 单点转换相关
const singlePoint = reactive({
  lng: 116.3913,
  lat: 39.9075,
  fromType: 'wgs84'
});
const singlePointResult = ref(null);

// 批量转换相关
const batchTransform = reactive({
  fromType: 'wgs84',
  toType: 'gcj02',
  coordinates: '116.3913, 39.9075\n121.4737, 31.2304\n113.2644, 23.1291'
});
const batchResult = ref(null);

// 距离计算相关
const distancePoint1 = reactive({ lng: 116.3913, lat: 39.9075 });
const distancePoint2 = reactive({ lng: 116.3974, lat: 39.9087 });
const distanceResult = ref(null);

// 标记点实体数组
let markerEntities = [];

onMounted(() => {
  // 初始化地图
  cesiumMap = new CesiumMap(mapContainer.value, {
    animation: false,
    timeline: false,
    baseLayerPicker: false,
    geocoder: false,
    homeButton: false,
    sceneModePicker: false,
    navigationHelpButton: false,
    infoBox: false
  });
  
  setTimeout(() => {
    console.log('CesiumMap initialized successfully');
    
    // 测试坐标转换功能
    console.log('测试坐标转换功能...');
    try {
      const testResult = CoordinateTransform.wgs84ToGcj02(116.3913, 39.9075);
      console.log('测试转换结果:', testResult);
    } catch (error) {
      console.error('测试转换失败:', error);
    }
  }, 1000);
});

onBeforeUnmount(() => {
  if (cesiumMap) {
    cesiumMap.destroy();
  }
});

// 获取坐标系名称
const getSystemName = (systemCode) => {
  return CoordinateTransform.getSystemName(systemCode);
};

// 获取坐标系信息
const getSystemInfo = (systemCode) => {
  return CoordinateTransform.getSystemInfo(systemCode);
};

// 切换坐标系信息显示
const toggleSystemInfo = (system) => {
  const index = expandedSystems.value.indexOf(system);
  if (index > -1) {
    expandedSystems.value.splice(index, 1);
  } else {
    expandedSystems.value.push(system);
  }
};

// 格式化坐标显示
const formatCoordinate = (lng, lat, precision = 6) => {
  return CoordinateTransform.formatCoordinate(lng, lat, precision);
};

// 单点转换
const transformSinglePoint = () => {
  try {
    console.log('开始坐标转换...');
    console.log('输入坐标:', singlePoint);
    
    const lng = parseFloat(singlePoint.lng);
    const lat = parseFloat(singlePoint.lat);
    
    console.log('解析后的坐标:', { lng, lat });
    
    if (!CoordinateTransform.isValidCoordinate(lng, lat)) {
      alert('请输入有效的坐标');
      return;
    }

    // 先测试基本转换
    console.log('测试基本转换...');
    let wgs84, gcj02, bd09;
    
    switch (singlePoint.fromType) {
      case 'wgs84':
        wgs84 = { lng, lat };
        gcj02 = CoordinateTransform.wgs84ToGcj02(lng, lat);
        bd09 = CoordinateTransform.wgs84ToBd09(lng, lat);
        break;
      case 'gcj02':
        gcj02 = { lng, lat };
        wgs84 = CoordinateTransform.gcj02ToWgs84(lng, lat);
        bd09 = CoordinateTransform.gcj02ToBd09(lng, lat);
        break;
      case 'bd09':
        bd09 = { lng, lat };
        gcj02 = CoordinateTransform.bd09ToGcj02(lng, lat);
        wgs84 = CoordinateTransform.bd09ToWgs84(lng, lat);
        break;
      default:
        wgs84 = { lng, lat };
        gcj02 = CoordinateTransform.wgs84ToGcj02(lng, lat);
        bd09 = CoordinateTransform.wgs84ToBd09(lng, lat);
    }

    const result = {
      wgs84,
      gcj02,
      bd09,
      cgcs2000: wgs84, // CGCS2000 与 WGS84 基本相同
      xian80: wgs84,   // 简化处理
      beijing54: wgs84, // 简化处理
      epsg3857: CoordinateTransform.wgs84ToEpsg3857(wgs84.lng, wgs84.lat),
      epsg4326: wgs84
    };

    singlePointResult.value = result;
    console.log('坐标转换完成:', result);
  } catch (error) {
    console.error('坐标转换失败:', error);
    alert('转换失败: ' + error.message);
  }
};

// 批量转换
const transformBatch = () => {
  try {
    const coordLines = batchTransform.coordinates.trim().split('\n');
    const coordinates = [];
    
    for (const line of coordLines) {
      const coord = CoordinateTransform.parseCoordinate(line);
      if (coord) {
        coordinates.push(coord);
      }
    }
    
    if (coordinates.length === 0) {
      alert('请输入有效的坐标');
      return;
    }

    batchResult.value = CoordinateTransform.transformCoordinates(
      coordinates, 
      batchTransform.fromType, 
      batchTransform.toType
    );
    
    console.log('批量转换结果:', batchResult.value);
  } catch (error) {
    alert('批量转换失败: ' + error.message);
  }
};

// 飞行到指定坐标
const flyToCoordinate = (lng, lat) => {
  if (!cesiumMap || !cesiumMap.viewer) {
    console.warn('CesiumMap not ready');
    return;
  }
  
  console.log('飞行到坐标:', lng, lat);
  // cesiumMap.flyTo({
  //   destination: Cesium.Cartesian3.fromDegrees(lng, lat, 1000),
  //   duration: 2
  // });
};

// 计算距离
const calculateDistance = () => {
  try {
    const lng1 = parseFloat(distancePoint1.lng);
    const lat1 = parseFloat(distancePoint1.lat);
    const lng2 = parseFloat(distancePoint2.lng);
    const lat2 = parseFloat(distancePoint2.lat);
    
    if (!CoordinateTransform.isValidCoordinate(lng1, lat1) || 
        !CoordinateTransform.isValidCoordinate(lng2, lat2)) {
      alert('请输入有效的坐标');
      return;
    }

    distanceResult.value = CoordinateTransform.calculateDistance(lng1, lat1, lng2, lat2);
    console.log('距离计算结果:', distanceResult.value);
  } catch (error) {
    alert('距离计算失败: ' + error.message);
  }
};

// 加载预设坐标
const loadPreset = (city) => {
  const presets = {
    beijing: { lng: 116.3913, lat: 39.9075, name: '北京天安门' },
    shanghai: { lng: 121.4737, lat: 31.2304, name: '上海外滩' },
    guangzhou: { lng: 113.2644, lat: 23.1291, name: '广州塔' },
    shenzhen: { lng: 114.0579, lat: 22.5431, name: '深圳平安金融中心' },
    xian: { lng: 108.9398, lat: 34.2594, name: '西安钟楼' },
    chengdu: { lng: 104.0668, lat: 30.5728, name: '成都天府广场' }
  };

  const preset = presets[city];
  if (preset) {
    singlePoint.lng = preset.lng;
    singlePoint.lat = preset.lat;
    singlePoint.fromType = 'wgs84';
    transformSinglePoint();
  }
};
</script>

<style scoped>
.coordinate-transform-demo {
  width: 100%;
  height: 100vh;
  display: flex;
  background: #f5f5f5;
}

.demo-container {
  display: flex;
  width: 100%;
  height: 100%;
}

.transform-panel {
  width: 450px;
  background: white;
  padding: 20px;
  overflow-y: auto;
  box-shadow: 2px 0 8px rgba(0,0,0,0.1);
}

.transform-panel h2 {
  margin-top: 0;
  color: #333;
  border-bottom: 3px solid #409eff;
  padding-bottom: 10px;
}

.subtitle {
  color: #666;
  font-size: 14px;
  margin-bottom: 20px;
}

.section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  background: #f8f9fa;
}

.section h3 {
  margin-top: 0;
  color: #495057;
  font-size: 18px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.input-group label {
  font-weight: bold;
  color: #495057;
}

.input-group input,
.input-group select,
.input-group textarea {
  padding: 8px 12px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 14px;
}

.input-group textarea {
  resize: vertical;
  min-height: 80px;
}

.input-group input:focus,
.input-group select:focus,
.input-group textarea:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.point-input {
  display: flex;
  gap: 8px;
  align-items: center;
}

.point-input input {
  flex: 1;
}

.transform-btn {
  padding: 10px 20px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  transition: background 0.2s;
}

.transform-btn:hover {
  background: #66b1ff;
}

.result {
  margin-top: 16px;
  padding: 16px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.result h4 {
  margin-top: 0;
  color: #333;
  font-size: 16px;
}

.result-grid {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.result-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.result-item strong {
  color: #333;
  font-size: 14px;
  min-width: 120px;
}

.locate-btn {
  padding: 6px 12px;
  background: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background 0.2s;
}

.locate-btn.small {
  padding: 4px 8px;
  font-size: 11px;
}

.locate-btn:hover {
  background: #218838;
}

.batch-result {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.batch-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
}

.coord-index {
  font-weight: bold;
  color: #666;
  min-width: 30px;
}

.coord-value {
  flex: 1;
  font-family: monospace;
}

.preset-buttons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.preset-buttons button {
  padding: 8px 12px;
  background: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background 0.2s;
}

.preset-buttons button:hover {
  background: #545b62;
}

.system-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.system-item {
  border: 1px solid #dee2e6;
  border-radius: 4px;
  overflow: hidden;
}

.system-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 12px;
  background: #f8f9fa;
  cursor: pointer;
  transition: background 0.2s;
}

.system-header:hover {
  background: #e9ecef;
}

.system-name {
  font-weight: bold;
  color: #495057;
}

.toggle-icon {
  font-weight: bold;
  color: #6c757d;
  font-size: 18px;
}

.system-details {
  padding: 12px;
  background: white;
  border-top: 1px solid #dee2e6;
}

.system-details p {
  margin: 5px 0;
  font-size: 13px;
  color: #666;
}

.map-container {
  flex: 1;
  position: relative;
}

.cesium-map {
  width: 100%;
  height: 100%;
}

.map-info {
  position: absolute;
  bottom: 20px;
  left: 20px;
  background: rgba(255, 255, 255, 0.95);
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  max-width: 300px;
}

.map-info p {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #333;
}

.map-info ul {
  margin: 0;
  padding-left: 20px;
}

.map-info li {
  margin: 5px 0;
  font-size: 13px;
  color: #666;
  display: flex;
  align-items: center;
}

.color-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 8px;
  border: 1px solid #ccc;
}

.color-dot.wgs84 {
  background: #28a745;
}

.color-dot.gcj02 {
  background: #fd7e14;
}

.color-dot.bd09 {
  background: #6f42c1;
}

.color-dot.cgcs2000 {
  background: #17a2b8;
}

.no-locate {
  color: #666;
  font-size: 12px;
  font-style: italic;
  padding: 4px 8px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #dee2e6;
}
</style> 